package edu.gatech.cs2340.teamrocket.control.networking.dialog;

import java.io.EOFException;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.net.Socket;
import edu.gatech.cs2340.teamrocket.control.networking.message.Message;

/**
 * Listens for new Message objects over a socket and sends them to the Dialog
 * and in turn, the Endpoint and MessageHandler for handling.
 *
 * @author Joe Tacheron
 */
public class MessageListener implements Runnable {

    private Dialog dialog;
    private ObjectInputStream in;
    private volatile boolean quit;

    public MessageListener(Dialog dialog, Socket socket) throws IOException{
        this.dialog = dialog;
        this.in = new ObjectInputStream(socket.getInputStream());
    }

    /**
     * Listen for new Messages over the Socket and send them to the owning Dialog.
     */
    @Override
    public void run(){
        while(!quit){
            try {
                dialog.handle((Message)in.readObject());
            }
            catch (EOFException e){
                dialog.close();
            }
            catch (IOException e) {
                e.printStackTrace();
            }
            catch(ClassNotFoundException e){
                e.printStackTrace();
            }
        }
    }

    /**
     * End this thread.
     */
    public void close(){
        quit = true;
    }
}
